//
//  LoginViewController.m
//  Lmm_IOS
//
//  Created by 张哲炜 on 2018/9/20.
//  Copyright © 2018年 lmm. All rights reserved.
//

#import "LoginViewController.h"

@interface LoginViewController (){
    
    UIView *addView;
    UITextField *numberTextField;
    UITextField *passWordTextField;
    NSMutableAttributedString *aStr;
    
    UIButton *verifybutton;
    
    NSTimer *timer;
    int countdown;
}

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self drawView];
    
    
    
    // Do any additional setup after loading the view.
}



- (void)drawView {
    
     addView =UIView.new;
    [self.view addSubview:addView];
    
    [addView makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.top).offset(20);
        make.left.equalTo(self.view.left).offset(0);
        make.right.equalTo(self.view.right).offset(0);
        make.bottom.equalTo(self.view.bottom).offset(0);
        
    }];
    
    
    UIImageView *backImageView =UIImageView.new;
    [backImageView setImage:[UIImage imageNamed:@"back"]];
     
     [addView addSubview:backImageView];
    
     [backImageView makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self->addView.left).offset(10);
        make.top.equalTo(self->addView.top).offset(20);
        make.width.equalTo(10);
        make.height.equalTo(18.5);
    }];
    
    
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [backButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [addView addSubview:backButton];
    
    [backButton makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self->addView.left).offset(10);
        make.top.equalTo(self->addView.top).offset(20);
        make.width.equalTo(50);
        make.height.equalTo(30);
    }];
    
    
    UILabel *titleLabel =UILabel.new;
    titleLabel.text = @"登陆/注册";
    titleLabel.font =[UIFont systemFontOfSize:20];
    [self.view addSubview:titleLabel];
    
    [titleLabel makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.centerX);
        make.top.equalTo(self.view.top).offset(100);
        make.height.equalTo(20);
        
    }];

    
    UIView *divideLine0_left = UIView.new;
    divideLine0_left.backgroundColor = UIColorFromRGB(0xE8564F);
    [self.view addSubview:divideLine0_left];
    
    [divideLine0_left makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(titleLabel.bottom).offset(30);
        make.left.equalTo(self.view.left).offset(40);
        make.width.equalTo(80);
        make.height.equalTo(2);
    }];
    
    UIView *divideLine0_right = UIView.new;
    divideLine0_right.backgroundColor = UIColorFromRGB(0xE2E2E2);
    [self.view addSubview:divideLine0_right];
    
    [divideLine0_right makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(divideLine0_left.top).offset(0);
        make.left.equalTo(divideLine0_left.right).offset(0);
        make.right.equalTo(self.view.right).offset(-40);
        make.height.equalTo(2);
    }];
    
    
    UILabel *numberLabel = UILabel.new;
    numberLabel.text = @"手机号";
    numberLabel.textColor=UIColorFromRGB(0x999999);
    numberLabel.font=[UIFont systemFontOfSize:15];
    [self.view addSubview:numberLabel ];
    
    [ numberLabel makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(titleLabel.top).offset(100);
        make.left.equalTo(self.view.left).offset(30);
        make.height.equalTo(15);
    }];
    
    
    numberTextField = UITextField.new;
    numberTextField.backgroundColor =[UIColor whiteColor];
    numberTextField.font = [UIFont systemFontOfSize:15];
    numberTextField.textColor = UIColorFromRGB(0xD0D0D0);
    numberTextField.clearButtonMode = UITextFieldViewModeAlways;
    numberTextField.placeholder = @"请输入手机号";
    numberTextField.keyboardType = UIKeyboardTypePhonePad;
    numberTextField.borderStyle = UITextBorderStyleNone;
    
    [self.view addSubview:numberTextField];
    
    [numberTextField makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(numberLabel.bottom).offset(7);
        make.left.equalTo(self.view.left).offset(30);
        make.right.equalTo(self.view.right).offset(-30);
        make.height.equalTo(40);
    }];
    
    
    UILabel *passwordLabel = UILabel.new;
    passwordLabel.textColor = UIColorFromRGB(0x999999);
    passwordLabel.text = @"验证码";
    passwordLabel.font=[UIFont systemFontOfSize:15];
    [self.view addSubview:passwordLabel];
    
    [passwordLabel makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self->numberTextField.bottom).offset(20);
        make.left.equalTo(self.view.left).offset(30);
        make.height.equalTo(15);
    }];
    
    
    passWordTextField = UITextField.new;
    passWordTextField.backgroundColor =[UIColor whiteColor];
    passWordTextField.font = [UIFont systemFontOfSize:15];
    passWordTextField.textColor = UIColorFromRGB(0xD0D0D0);
    passWordTextField.clearButtonMode = UITextFieldViewModeAlways;
    passWordTextField.placeholder = @"请输入验证码";
    passWordTextField.keyboardType = UIKeyboardTypePhonePad;
    passWordTextField.borderStyle = UITextBorderStyleNone;
    [self.view addSubview:passWordTextField];
    
    [passWordTextField makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(passwordLabel.bottom).offset(7);
        make.left.equalTo(self.view.left).offset(30);
        make.right.equalTo(self.view.right).offset(-30);
        make.height.equalTo(40);
        
    }];
    
    
    UIView *divideLine1 = UIView.new;
    divideLine1.backgroundColor = UIColorFromRGB(0xCCCCCC);
    [self.view addSubview:divideLine1];
    
    [divideLine1 makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self->numberTextField.bottom).offset(10);
        make.left.equalTo(self.view.left).offset(30);
        make.right.equalTo(self.view.right).offset(-30);
        make.height.equalTo(1/[[UIScreen mainScreen] scale]);
        
    }];
    
    
    verifybutton =UIButton.new;
    [verifybutton setTitle:@"获取验证码" forState:UIControlStateNormal];
    [verifybutton setTitleColor:[UIColor redColor]forState:UIControlStateNormal];
    verifybutton.titleLabel.font = [UIFont systemFontOfSize:13];
    verifybutton.layer.cornerRadius=16;
    verifybutton.layer.borderColor=[UIColor redColor].CGColor;
    verifybutton.layer.borderWidth = 1;
    [verifybutton addTarget:self action:@selector(showCaptchaImageView) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:verifybutton];
    
    [verifybutton makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self->passWordTextField.right).offset(-10);
        make.top.equalTo(self->passWordTextField.top).offset(4);
        make.bottom.equalTo(self->passWordTextField.bottom).offset(-4);
        make.width.equalTo(100);
    }];
    [verifybutton addTarget:self action:@selector(showCaptchaImageView) forControlEvents:(UIControlEventTouchUpInside)];
    
    
    UIView *divideLine2 = UIView.new;
    divideLine2.backgroundColor = UIColorFromRGB(0xCCCCCC);
    [self.view addSubview:divideLine2];
    
    [divideLine2 makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self->passWordTextField.bottom).offset(10);
        make.left.equalTo(self.view.left).offset(30);
        make.right.equalTo(self.view.right).offset(-30);
        make.height.equalTo(1/[[UIScreen mainScreen]scale]);
        
    }];
    
    
    NSString *str = @"我已阅读并同意零买买使用协议";
    // 2.将字符串拆分，按照需要展现的颜色或字体的不同拆分成多个单独的字符串，并转化成NSRange格式；
    NSRange rangeA = [str rangeOfString:@"我已阅读并同意"];
    NSRange rangeB = [str rangeOfString:@"零买买使用协议"];
    
    // 3.将 1.中创建的字符串生成可自由设置的 NSMutableAttributedString
    aStr = [[NSMutableAttributedString alloc] initWithString:str];
    // 4.给每一部分分别设置颜色
    [aStr addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:rangeA];
    [aStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:rangeB];
    
    
    UILabel *protocolLabel =UILabel.new;
    protocolLabel.attributedText = aStr;
    protocolLabel.font=[UIFont systemFontOfSize:14];
    [self.view addSubview:protocolLabel];
    
    [ protocolLabel makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.left).offset(40);
        make.right.equalTo(self.view.right).offset(-30);
        make.top.equalTo(divideLine2.bottom).offset(7);
        make.height.equalTo(30);
    }];
    
    
    UIButton *Loginbutton=UIButton.new;
    [Loginbutton setTitle:@"登陆/注册" forState:(UIControlStateNormal)];
    Loginbutton.backgroundColor = UIColorFromRGB(0xE8564F);
    [Loginbutton setTitleColor:[UIColor whiteColor]forState:UIControlStateNormal];
    Loginbutton.layer.cornerRadius=10;
    Loginbutton.layer.borderColor=[UIColor clearColor].CGColor;
    Loginbutton.layer.borderWidth=2;
    [Loginbutton addTarget:self action:@selector(LogIn) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:Loginbutton];
    
    [Loginbutton makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(protocolLabel.bottom).offset(40);
        make.left.equalTo(self.view.left).offset(30);
        make.right.equalTo(self.view.right).offset(-30);
        make.height.equalTo(50);
    }];
    //手势
    UISwipeGestureRecognizer* swipe= [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipeBack :)];
    [self.view addGestureRecognizer:swipe];
    
    
    }



- (void) showCaptchaImageView {
    
        NSString *mobile = self->numberTextField.text;
    
        if (mobile.length == 0) {
            [Tool showHUD:@"手机号不能为空！"  : self.view];
            return;
        }

        if (![Tool isMobile:mobile]) {
            [Tool showHUD:@"手机号格式不正确！" : self.view];
            return;
        }

        verifybutton.enabled = NO;

    CaptchaImageView *captchaImageView = [[CaptchaImageView alloc] init:^(NSString *captcha) {
        
        NSLog(@"%@",  captcha);
        
        // http://39.104.87.146/app/sms?mobile=1234567&captcha=3456&
        NSMutableDictionary *params = NSMutableDictionary.new;
        [params setValue:self->numberTextField.text forKey:@"mobile"];
        [params setValue: captcha forKey:@"captcha"];
        
        [HttpHelper request:@"app/sms" :@"POST" :params successBlock:^(NSDictionary *responseDic) {
            //NSLog(@"%@",responseDic);
            MessageModel* msg = [MessageModel mj_objectWithKeyValues:responseDic];

                if (msg.code != 0) {
                    [Tool showHUD:msg.message  :self.view];
                    return;
                }
    
                [Tool showHUD:@"验证码发送成功！" :self.view];
                self->countdown = 60;
                self->timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(refreshTime) userInfo:nil repeats:YES];
                [self->timer fire];
            
            
        } failureBlock:^(NSError *error) {
            
            
            
        }];
        
        
        

    }];
    [self.view addSubview:captchaImageView];
}


- (void) refreshTime {
    
    if (self->countdown == 0) {

        if (self->timer && [self->timer isValid]) {
            [self->timer invalidate];
            self->timer = nil;
        }

        self->verifybutton.enabled = YES;
        [self->verifybutton setTitle:@"获取验证码" forState:UIControlStateNormal];
        self->verifybutton.backgroundColor = [UIColor clearColor];
        [self->verifybutton setTitleColor:MAIN_COLOR forState:UIControlStateNormal];
    } else {
        self->verifybutton.backgroundColor = MAIN_COLOR;
        [self->verifybutton setTitleColor:UIColorFromRGB(0xFFFFFF) forState:UIControlStateNormal];

        [self->verifybutton setTitle:[NSString stringWithFormat:@"重新获取%ds", self->countdown] forState:UIControlStateNormal];
        self->countdown--;
    }
    
    //[self->verifybutton layoutIfNeeded];
}


- (void) LogIn {
    
    
    NSString *mobile = self->numberTextField.text;

    if (mobile.length == 0) {
        [Tool showHUD:@"手机号不能为空！"  : self.view];
        return;
    }

    if (![Tool isMobile:mobile]) {
        [Tool showHUD:@"手机号格式不正确！" : self.view];
        return;
    }

    NSString *captcha =self->passWordTextField.text;

    if (captcha.length == 0) {
        [Tool showHUD:@"验证码不能为空！"  : self.view];
        return;
    }

    NSMutableDictionary *params = NSMutableDictionary.new;
    [params setValue:self->numberTextField.text forKey:@"mobile"];
    [params setValue: captcha forKey:@"captcha"];

    [HttpHelper request:@"user/login" :@"POST" :params successBlock:^(NSDictionary *responseDic) {

        MessageModel *msg = [MessageModel mj_objectWithKeyValues:responseDic ];

        if (msg.code != 0) {
            [Tool showHUD:msg.message  :self.view];
            return;
        }
           [Tool showHUD:@"登录成功" :self.view];

        UserModel *user = [UserModel mj_objectWithKeyValues:responseDic[@"data"]];

        [[PINCache sharedCache]setObject:user forKey:@"user"];

        //NSLog(@"%@",user.avatar);

        //发通知
        [[NSNotificationCenter defaultCenter] postNotificationName:@"LoginEvent" object:self userInfo:nil];

        [self back];

    } failureBlock:^(NSError *error) {

    }];
    
  
   
}

//轻扫手势回到上一页
- (void)swipeBack :(UISwipeGestureRecognizer * )swipe
{
    
    if((swipe.direction = UISwipeGestureRecognizerDirectionRight))
    {
        [self back];
    }
    
}



- (void) back {
    
    //返回页面时，将用户的计时器移除
    if (self->timer && [self->timer isValid]) {
        [self->timer invalidate];
        self->timer = nil;
    } 
    
    //点击按钮跳转页面
    [self.navigationController popViewControllerAnimated:YES];
}


//键盘设置第一响应者
- (void) touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    [passWordTextField resignFirstResponder];
    [numberTextField resignFirstResponder];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
